/**
 * 增强版问答面板组件
 * 提供基于热点的智能提示，让用户获得更多启发
 */
import React, { useState, useEffect } from 'react';
import { Card, Input, Button, Space, Progress, message, Tooltip, Tag, Alert } from 'antd';
import {
  ArrowLeftOutlined,
  ArrowRightOutlined,
  ReloadOutlined,
  QuestionCircleOutlined,
  BulbOutlined,
  FireOutlined,
  ThunderboltOutlined,
  BookOutlined,
} from '@ant-design/icons';
import { useBrainstormStore } from '@/stores/brainstorm.store';
import { brainstormService } from '@/services/brainstorm.service';
import { debounce } from '@/utils/brainstorm-helpers';
import './style.css';

const { TextArea } = Input;

export interface EnhancedQuestionPanelProps {
  onComplete?: () => void;
  hotTopicData?: {
    title: string;
    platform: string;
    category: string;
    heatValue: number;
    tags: string[];
    relatedTopics?: string[];
  };
}

// 根据问题目的和热点数据生成智能提示
const generateSmartHints = (
  purpose: string,
  hotTopicData?: any
): { hint: string; examples: string[]; tips: string[] } => {
  const baseHints = {
    audience: {
      hint: '想想谁会对这个话题感兴趣？他们的年龄、职业、兴趣是什么？',
      examples: [
        '关注科技趋势的年轻专业人士',
        '对育儿感兴趣的新手父母',
        '热爱美食的都市白领',
        '追求健康生活的中年群体',
      ],
      tips: [
        '考虑读者的知识背景',
        '思考读者的痛点和需求',
        '明确读者的阅读场景',
      ],
    },
    viewpoint: {
      hint: '你对这个话题有什么独特见解？可以从哪个新角度切入？',
      examples: [
        '从长远发展角度看，这其实是一个机遇',
        '表面看是技术问题，实质是管理问题',
        '这不仅是个人选择，更是时代趋势',
        '与其担心风险，不如主动拥抱变化',
      ],
      tips: [
        '避免人云亦云的观点',
        '结合个人经历或专业背景',
        '提出有争议但有理有据的看法',
      ],
    },
    material: {
      hint: '你有哪些相关经历、数据或案例可以支撑你的观点？',
      examples: [
        '我在某项目中的亲身经历',
        '最新的行业报告显示...',
        '某知名企业的成功案例',
        '身边朋友的真实故事',
      ],
      tips: [
        '优先使用第一手资料',
        '引用权威数据增加说服力',
        '故事比道理更容易打动人',
      ],
    },
    style: {
      hint: '你想用什么风格来表达？严肃分析还是轻松幽默？',
      examples: [
        '深度分析，数据驱动',
        '故事化叙述，娓娓道来',
        '轻松幽默，贴近生活',
        '专业严谨，逻辑清晰',
      ],
      tips: [
        '风格要符合目标读者喜好',
        '保持全文风格一致',
        '选择你最擅长的表达方式',
      ],
    },
    goal: {
      hint: '你希望读者看完文章后有什么收获或行动？',
      examples: [
        '获得实用的解决方案',
        '改变固有认知',
        '产生情感共鸣',
        '激发行动意愿',
      ],
      tips: [
        '目标要具体可衡量',
        '考虑读者的实际需求',
        '设定合理的期望值',
      ],
    },
  };

  const purposeData = baseHints[purpose as keyof typeof baseHints] || baseHints.viewpoint;

  // 如果有热点数据，生成更针对性的提示
  if (hotTopicData) {
    const { title, platform, tags, heatValue } = hotTopicData;

    // 根据热度调整提示
    if (heatValue > 80) {
      purposeData.tips.unshift('⚡ 热度很高，抓住时机快速发布');
    }

    // 根据平台特点调整
    const platformTips: Record<string, string> = {
      weibo: '微博用户喜欢简短有力的观点',
      zhihu: '知乎用户偏好深度分析和专业见解',
      douyin: '抖音用户喜欢视觉化、故事化的内容',
      xiaohongshu: '小红书用户关注实用性和生活品质',
    };

    if (platformTips[platform]) {
      purposeData.tips.push(`💡 ${platformTips[platform]}`);
    }

    // 根据标签生成相关示例
    if (tags && tags.length > 0) {
      const tagExamples = tags.slice(0, 3).map(tag =>
        `围绕"${tag}"展开讨论`
      );
      purposeData.examples = [...tagExamples, ...purposeData.examples.slice(0, 2)];
    }
  }

  return purposeData;
};

// 智能提示卡片组件
const SmartHintCard: React.FC<{
  hints: { hint: string; examples: string[]; tips: string[] };
  onSelectExample: (example: string) => void;
}> = ({ hints, onSelectExample }) => (
  <Card className="smart-hint-card" size="small">
    <div className="hint-header">
      <BulbOutlined style={{ color: '#faad14' }} />
      <span>智能提示</span>
    </div>

    <div className="hint-content">
      <div className="hint-main">
        {hints.hint}
      </div>

      <div className="hint-examples">
        <div className="hint-label">参考示例：</div>
        <Space wrap>
          {hints.examples.map((example, index) => (
            <Tag
              key={index}
              className="example-tag"
              color="blue"
              onClick={() => onSelectExample(example)}
              style={{ cursor: 'pointer' }}
            >
              {example}
            </Tag>
          ))}
        </Space>
      </div>

      <div className="hint-tips">
        {hints.tips.map((tip, index) => (
          <div key={index} className="tip-item">
            <ThunderboltOutlined style={{ color: '#52c41a', marginRight: 4 }} />
            {tip}
          </div>
        ))}
      </div>
    </div>
  </Card>
);

// 相关热点推荐组件
const RelatedTopics: React.FC<{
  topics?: string[];
  onSelect: (topic: string) => void;
}> = ({ topics, onSelect }) => {
  if (!topics || topics.length === 0) return null;

  return (
    <Alert
      message="相关热点"
      description={
        <Space wrap>
          {topics.map((topic, index) => (
            <Button
              key={index}
              size="small"
              icon={<FireOutlined />}
              onClick={() => onSelect(topic)}
            >
              {topic}
            </Button>
          ))}
        </Space>
      }
      type="info"
      showIcon
      icon={<FireOutlined />}
      className="related-topics-alert"
    />
  );
};

export const EnhancedQuestionPanel: React.FC<EnhancedQuestionPanelProps> = ({
  onComplete,
  hotTopicData
}) => {
  const { currentSession, updateSession } = useBrainstormStore();
  const [currentIndex, setCurrentIndex] = useState(0);
  const [answer, setAnswer] = useState('');
  const [loading, setLoading] = useState(false);
  const [showHints, setShowHints] = useState(true);

  const questions = currentSession?.questions || [];
  const currentQuestion = questions[currentIndex];
  const progress = questions.length > 0 ? ((currentIndex + 1) / questions.length) * 100 : 0;

  // 获取当前问题的智能提示
  const smartHints = currentQuestion
    ? generateSmartHints(currentQuestion.purpose, hotTopicData)
    : null;

  // 加载当前问题的答案
  useEffect(() => {
    if (currentQuestion) {
      setAnswer(currentQuestion.answer || '');
    }
  }, [currentQuestion]);

  // 自动保存答案（防抖3秒）
  const autoSave = debounce(async (questionId: string, answerText: string) => {
    if (!currentSession) return;

    try {
      await brainstormService.saveAnswer(currentSession.id, questionId, answerText);
    } catch (error) {
      console.error('Auto save failed:', error);
    }
  }, 3000);

  const handleAnswerChange = (value: string) => {
    setAnswer(value);

    // 更新Store
    if (currentQuestion && currentSession) {
      const updatedQuestions = questions.map((q) =>
        q.id === currentQuestion.id ? { ...q, answer: value, skipped: false } : q
      );
      updateSession({ questions: updatedQuestions });
    }

    // 自动保存
    if (currentQuestion) {
      autoSave(currentQuestion.id, value);
    }
  };

  const handleSelectExample = (example: string) => {
    const currentAnswer = answer.trim();
    const newAnswer = currentAnswer
      ? `${currentAnswer}\n\n${example}`
      : example;
    handleAnswerChange(newAnswer);
    message.success('已添加到回答中');
  };

  const handleSelectRelatedTopic = (topic: string) => {
    const currentAnswer = answer.trim();
    const newAnswer = currentAnswer
      ? `${currentAnswer}\n\n关于"${topic}"的思考：`
      : `关于"${topic}"的思考：`;
    handleAnswerChange(newAnswer);
  };

  const handleNext = () => {
    if (currentIndex < questions.length - 1) {
      setCurrentIndex(currentIndex + 1);
    } else {
      // 完成所有问题
      if (onComplete) {
        onComplete();
      }
    }
  };

  const handlePrevious = () => {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1);
    }
  };

  const handleSkip = () => {
    if (!currentQuestion || !currentSession) return;

    // 标记为跳过
    const updatedQuestions = questions.map((q) =>
      q.id === currentQuestion.id ? { ...q, skipped: true, answer: '' } : q
    );
    updateSession({ questions: updatedQuestions });

    message.info('已跳过当前问题');
    handleNext();
  };

  const handleRegenerate = async () => {
    if (!currentQuestion || !currentSession) return;

    setLoading(true);
    try {
      const newQuestion = await brainstormService.generateQuestions(currentSession.id, 1);

      if (newQuestion.length > 0) {
        // 替换当前问题
        const updatedQuestions = questions.map((q, index) =>
          index === currentIndex ? newQuestion[0] : q
        );
        updateSession({ questions: updatedQuestions });
        setAnswer('');
        message.success('已生成新问题');
      }
    } catch (error) {
      message.error('重新生成失败');
      console.error('Regenerate question failed:', error);
    } finally {
      setLoading(false);
    }
  };

  if (!currentQuestion) {
    return (
      <div className="enhanced-question-panel empty">
        <Card>
          <p>暂无问题，请先创建会话</p>
        </Card>
      </div>
    );
  }

  return (
    <div className="enhanced-question-panel">
      {/* 热点信息栏 */}
      {hotTopicData && (
        <Card className="hot-topic-info" size="small">
          <Space>
            <FireOutlined style={{ color: '#ff4d4f' }} />
            <span className="topic-title">当前热点：{hotTopicData.title}</span>
            <Tag color="red">热度 {hotTopicData.heatValue}%</Tag>
            <Tag color="blue">{hotTopicData.platform}</Tag>
            {hotTopicData.tags?.map((tag, index) => (
              <Tag key={index}>{tag}</Tag>
            ))}
          </Space>
        </Card>
      )}

      {/* 进度条 */}
      <div className="progress-bar">
        <Progress
          percent={progress}
          showInfo={false}
          strokeColor={{
            '0%': '#1890ff',
            '100%': '#52c41a',
          }}
          strokeWidth={8}
        />
        <div className="progress-text">
          问题 {currentIndex + 1} / {questions.length}
        </div>
      </div>

      {/* 主要内容区 */}
      <div className="question-content-area">
        <div className="question-main">
          {/* 问题卡片 */}
          <Card className="question-card" bordered={false}>
            <div className="question-header">
              <div className="question-type">
                {currentQuestion.purpose === 'audience' && '🎯 目标读者'}
                {currentQuestion.purpose === 'viewpoint' && '💡 核心观点'}
                {currentQuestion.purpose === 'material' && '📚 素材来源'}
                {currentQuestion.purpose === 'style' && '✨ 文章风格'}
                {currentQuestion.purpose === 'goal' && '🎁 期望效果'}
              </div>
              <Space>
                <Button
                  size="small"
                  icon={<BulbOutlined />}
                  onClick={() => setShowHints(!showHints)}
                >
                  {showHints ? '隐藏' : '显示'}提示
                </Button>
                {currentQuestion.skipped && (
                  <span className="skipped-badge">已跳过</span>
                )}
              </Space>
            </div>

            <div className="question-text">
              {currentQuestion.text}
            </div>

            {currentQuestion.explanation && (
              <div className="question-explanation">
                <QuestionCircleOutlined style={{ marginRight: 6 }} />
                <span className="explanation-label">为什么问这个问题：</span>
                {currentQuestion.explanation}
              </div>
            )}

            <div className="answer-input">
              <TextArea
                value={answer}
                onChange={(e) => handleAnswerChange(e.target.value)}
                placeholder="请输入你的答案..."
                rows={8}
                maxLength={1000}
                showCount
                autoFocus
              />
            </div>

            {/* 相关热点推荐 */}
            {hotTopicData?.relatedTopics && (
              <RelatedTopics
                topics={hotTopicData.relatedTopics}
                onSelect={handleSelectRelatedTopic}
              />
            )}

            <div className="question-actions">
              <Space size={12}>
                <Button
                  icon={<ArrowLeftOutlined />}
                  onClick={handlePrevious}
                  disabled={currentIndex === 0}
                >
                  上一题
                </Button>

                <Button onClick={handleSkip} disabled={loading}>
                  跳过
                </Button>

                <Tooltip title="重新生成一个不同的问题">
                  <Button
                    icon={<ReloadOutlined />}
                    onClick={handleRegenerate}
                    loading={loading}
                  >
                    换个问题
                  </Button>
                </Tooltip>

                <Button
                  type="primary"
                  icon={<ArrowRightOutlined />}
                  onClick={handleNext}
                  disabled={loading}
                >
                  {currentIndex < questions.length - 1 ? '下一题' : '完成'}
                </Button>
              </Space>
            </div>
          </Card>
        </div>

        {/* 智能提示侧边栏 */}
        {showHints && smartHints && (
          <div className="hint-sidebar">
            <SmartHintCard
              hints={smartHints}
              onSelectExample={handleSelectExample}
            />

            {/* AI灵感助手 */}
            <Card className="inspiration-card" size="small">
              <div className="hint-header">
                <BookOutlined style={{ color: '#722ed1' }} />
                <span>AI灵感助手</span>
              </div>
              <Space direction="vertical" style={{ width: '100%' }}>
                <Button
                  block
                  icon={<ThunderboltOutlined />}
                  onClick={() => message.info('AI灵感生成中...')}
                >
                  生成创意角度
                </Button>
                <Button
                  block
                  icon={<BookOutlined />}
                  onClick={() => message.info('搜索相关资料中...')}
                >
                  查找相关素材
                </Button>
              </Space>
            </Card>
          </div>
        )}
      </div>

      {/* 底部提示 */}
      <div className="panel-tip">
        💡 提示：答案会自动保存，点击示例标签可快速添加到回答中
      </div>
    </div>
  );
};